package com.szr.leex.service.impl.user;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.szr.leex.po.user.LocalAuth;
import com.szr.leex.po.user.Role;
import com.szr.leex.service.user.LocalAuthService;
import com.szr.leex.service.user.UserService;

/**
 * 用户认证
 * Created by WangChen on 2018/10/12 16:46.
 */
@Transactional
@Service("userAuthenticateService")
public class UserAuthenticateServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private LocalAuthService localAuthService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.szr.leex.po.user.User user = userService.getByName(username);
        if (user == null){
            throw new UsernameNotFoundException("用户不存在！");
        }
        LocalAuth localAuth = localAuthService.getByUserId(user.getId());

        List<SimpleGrantedAuthority> simpleGrantedAuthorities = createAuthorities(user.getRoleList());
        return new User(user.getName(), localAuth.getPassword(), simpleGrantedAuthorities);
    }

    /**
     * 权限字符串转化
     *
     * 如 "USER,ADMIN" -> SimpleGrantedAuthority("USER") + SimpleGrantedAuthority("ADMIN")
     *
     */
    private List<SimpleGrantedAuthority> createAuthorities(List<Role> roleList){
//        String[] roles = roleStr.split(",");
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        for (Role role : roleList) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(role.getCode()));
        }
        return simpleGrantedAuthorities;
    }
}
